package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: jeason
 * @Description:
 * @Date: 2020/9/24 17:05
 */
class Dog implements Animal{
    @Override
    public void eat(){
        System.out.println("the dog is eating");
    }
}
class Cat implements Animal{
    @Override
    public void eat() {
        System.out.println("the cat is eating");
    }
}
public class JdkProxy implements InvocationHandler {
    private Object target;
    public Object getInstance(Object object){
        this.target = object;
        // 取得代理对象
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用前");
        Object result = method.invoke(target,args);
        System.out.println("调用后");
        return result;
    }

    public static void main(String[] args) {
        // JDK 动态代理调用
        JdkProxy proxy = new JdkProxy();
        Animal dogProxy = (Animal) proxy.getInstance(new Dog());
        dogProxy.eat();

    }
}
